package org.ejc.api.email;

import java.util.Date;

import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ejc.email.EmailMessage;


/**
 * @ejb:bean
 *    name="EmailMDB" 
 *    type="Message Driven"
 *    description="EJC session bean"
 *    destination-type="javax.jms.Queue"
 *    destination-jndi-name="queue/mail"
 *   
 * @ejb.resource-ref
 * 	  res-ref-name="jms/QueueFactory"
 *    jndi-name="java:/JmsXA"
 *    res-auth="Container" 
 * 
 * 
 * 
 * @jboss.destination-jndi-name name="queue/mail"
 * @jboss.resource-ref
 *  res-ref-name="jms/QueueFactory"
 *  jndi-name="java:/JmsXA"
 *  res-auth="Container"
 */

public  class EmailMDBean implements MessageDrivenBean,MessageListener{
   
    private static final long serialVersionUID = 1L;
    
    private static final String EOL=System.getProperty("line.separator");
    transient Context initial;
    transient javax.mail.Session session;
    
    /**
     * Logger for this class
     */
    private static final Log log = LogFactory.getLog(EmailMDBean.class);
     
    
    //around for the lifetime of this object
    MessageDrivenContext ejbContext;
    
    private static final String defaultFooter=
        "EJC 2006";
    
  
    public void ejbCreate(){
        try{
            Context initial = new InitialContext();
            session = (javax.mail.Session)initial.lookup("java:/Mail");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
  
    private boolean sendEmail(EmailMessage emailMessage){
        InternetAddress address[]=new InternetAddress[1];
        if(emailMessage.getRecipent()==null){
            log.fatal("Error Sending Email. No Reciepents have been specified. Who do we send the mail to ?");
            return false;
        }
        
        try {
            javax.mail.Message msg = new MimeMessage(session);
            msg.setFrom();
            address[0]=new InternetAddress(emailMessage.getRecipent(), false);
            msg.setRecipients(javax.mail.Message.RecipientType.TO, address);
            msg.setSubject(emailMessage.getSubject());
            if(emailMessage.isIncludeFooter()){
                msg.setText(emailMessage.getMessageText()+EOL+EOL+EOL+defaultFooter);
            }else{
                msg.setText(emailMessage.getMessageText());
            }
            
            msg.setSentDate(new Date());
            Transport.send(msg);
            log.fatal("Email Sent!!!!");
        } catch (Exception e) {
            log.fatal("Error while sending email!",e);
            
            return false;
        }
        
        
        return true;
    }
    
    
    public void onMessage(Message message){
        log.debug("Have got a message now ok ! "+message);
        try{
//            if(message instanceof ObjectMessage) {
//                //ObjectMessage txt = (ObjectMessage) message;
//                EmailMessage emailMessage=(EmailMessage)message;
//                sendEmail(emailMessage);
//            }
        	
        	if (message instanceof ObjectMessage)
        	{
        	Object o = ((ObjectMessage)message).getObject();
        	EmailMessage emailMsg=(EmailMessage)o;
        	System.out.println("Object was: " + o.getClass().getName());
        	sendEmail(emailMsg);
        	}
        	
        }catch(Exception e){
            log.fatal(e);
        }
    }
    
    
   
    public void setMessageDrivenContext(MessageDrivenContext mdc){
        ejbContext=mdc;
    }
    public void ejbRemove(){
        ejbContext=null;
    }
    
}
